package com.toe.admin.security.config;

import com.toe.admin.security.MyAccessDeniedHandler;
import com.toe.admin.security.MyAuthenticationEntryPoint;
import com.toe.admin.security.filter.SSOFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SSOWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private SSOFilter ssoFilter;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭防跨越攻击
        http.csrf().disable();

        // 放行清单
        String[] permitList = {
                "/**"
//                "/swagger-resources/**",    // Knife4j在线API文档的资源
//                "/v2/api-docs/**",          // Knife4j在线API文档的资源
//                "/favicon.ico",     // 网站图标文件
//                "/",                // 根页面，通常是主页
//                "/*.html",          // 任何html
//                "/**/*.html",       // 任何目录下的html
//                "/**/*.css",        // 任何目录下的css
//                "/**/*.js",         // 任何目录下的js
//                "/*/sso/login",     // 登录
//                "/*/sso/home"
        };

        // 配置各请求路径的认证与授权 , urlsHttpMethod.OPTIONS
        http.authorizeRequests() // 请求需要授权才可以访问
                .antMatchers(permitList) // 匹配一些路径
                .permitAll() // 允许直接访问（不需要经过认证和授权）
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                .anyRequest() // 匹配除了以上配置的其它请求
                .authenticated(); // 都需要认证


//        http.cors().configurationSource(corsConfigurationSource());
//        //关闭跨域
//        CorsConfigurer<HttpSecurity> cors = http.cors();
//        // Session管理
//        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
//        http.sessionManagement().sessionFixation().none();

//        //权限不足处理器
//        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
//        //未认证处理器
//        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint);
        // 添加自定义过滤器
        http.addFilterBefore(ssoFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
